#ifndef _UDP_SERVER_HPP__
#define _UDP_SERVER_HPP__

//服务器
#include<functional>
#include <iostream>
#include <string>
#include <memory>
#include <cstring>
#include <cerrno>
#include <strings.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "Log.hpp"
#include"Common.hpp"
#include"InetAddr.hpp"

using namespace LogModule;

const static int gsockfd = -1;
const static uint16_t gdefaultport = 8080;         // 端口号

using func_t = std::function<std::string(const std::string&)>; 

class UdpServer
{
public:
    UdpServer(func_t func, uint16_t port = gdefaultport)
        : _sockfd(gsockfd), _addr(port),_isrunning(false),_func(func)
    {
    }
    //创建
    void InitServer()
    {
        // 1. 创建sockfd
        _sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket:" << strerror(errno);
            // 进程退出
            Die(SOCKET_ERR);
        }
        LOG(LogLevel::INFO) << "socket success , sockfd is : " << _sockfd;

        // 2.2 bind :设置进入内核
        int n = ::bind(_sockfd, _addr.NetAddr(), _addr.NetAddrLen());
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind:" << strerror(errno);
            // 进程退出
            Die(BIND_ERR);
        }
        LOG(LogLevel::INFO) << "绑定成功" << strerror(errno);
    }
    //启动
    void Start()
    {
        _isrunning = true;
        while(true)
        {
            char inbuffer[1024];
            struct sockaddr_in peer;      //远端
            socklen_t len = sizeof(peer); //必须设定
            //受消息
            ssize_t n = ::recvfrom(_sockfd,inbuffer,sizeof(inbuffer)-1,0,CONV(&peer),&len);
            if(n > 0)
            {
                //发消息,把英文单词转化成中文
                inbuffer[n] = 0;
                std::string result = _func(inbuffer);
                ::sendto(_sockfd,result.c_str(),result.size(),0,CONV(&peer),sizeof(peer));

            }
        }
        _isrunning = false;
    }
    ~UdpServer()
    {
        if(_sockfd > gsockfd)
        {
            ::close(_sockfd);
        }
    }

private:
    int _sockfd;
    InetAddr _addr;  //服务器在哪个地址上
    bool _isrunning; // 服务器运行状态

    //业务，回调方法
    func_t _func;
};

#endif